package com.pureut.production.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.*;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.dto.storage.dto.WarehouseDto;
import com.pureut.production.domain.vo.PackageLabelVo;
import com.pureut.production.domain.vo.WarehousingVo;
import com.pureut.production.domain.vo.WeighingFinishedMaterialProductVo;
import com.pureut.production.mapper.*;
import com.pureut.production.service.CutOrdersDocumentService;
import com.pureut.production.service.WeighingFinishedMaterialProductDetailService;
import com.pureut.production.service.WeighingFinishedMaterialProductService;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.OrderFeignService;
import com.pureut.system.api.SchedulingPlanFeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.BackDataVo;
import com.pureut.system.api.vo.BackWeight;
import com.pureut.system.api.vo.WipOtherAddVo;
import com.pureut.system.api.vo.WmsStockInfoVo;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 成品称重表实现层
 * Author:C
 * Date:2023/02/24 13:57
 * @DESC
 */
@Service
public class WeighingFinishedMaterialProductServiceImpl extends ServiceImpl<WeighingFinishedMaterialProductMapper, WeighingFinishedMaterialProduct> implements WeighingFinishedMaterialProductService {


    @Resource
    WeighingFinishedMaterialProductMapper weighingFinishedMaterialProductMapper;

    @Resource
    WeighingFinishedMaterialProductDetailService weighingFinishedMaterialProductDetailService;

    @Resource
    WeighingFinishedMaterialProductDetailMapper weighingFinishedMaterialProductDetailMapper;

    @Lazy
    @Resource
    CutOrdersDocumentMapper cutOrdersDocumentMapper;

    @Lazy
    @Resource
    CutOrdersDocumentService cutOrdersDocumentService;

    @Resource
    CutOrdersDocumentDetailMapper cutOrdersDocumentDetailMapper;

    @Resource
    StorageFegin storageFegin;

    @Resource
    FeignService feignService;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    SchedulingPlanFeignService schedulingPlanFeignService;

    @Resource
    SysShopModelingMapper sysShopModelingMapper;

    @Resource
    MaterialFinishedMapper materialFinishedMapper;


    /**
     * 成品称重列表
     *
     * @param weighingFinishedMaterialProductVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<WeighingFinishedMaterialProductDto> getList(WeighingFinishedMaterialProductVo weighingFinishedMaterialProductVo) {

        //成品称重物料明细打印状态
        List<SysDictData> printStatusArray = DictUtils.getDictCache("weighing_finished_material_product_print_status");
        Map<String, String> printStatusMap = printStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //成品称重物料明细入库状态
        List<SysDictData> storageStatusArray = DictUtils.getDictCache("weighing_finished_material_product_storage_status");
        Map<String, String> storageStatusMap = storageStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //包装要求
        List<SysDictData> packingArray = DictUtils.getDictCache("sale_order_packing");
        Map<String, String> packingMap = packingArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //网型
        List<SysDictData> typeArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //班次
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        List<WeighingFinishedMaterialProductDto> list = weighingFinishedMaterialProductMapper.getList(weighingFinishedMaterialProductVo);

        for (WeighingFinishedMaterialProductDto entity : list) {
            entity.setPrintStatusDict(printStatusMap.get(entity.getPrintStatus()));
            entity.setStorageStatusDict(storageStatusMap.get(entity.getStorageStatus()));
            entity.setPackingRequirementDict(packingMap.get(entity.getPackingRequirement()));
            entity.setMaterialNetDict(typeMap.get(entity.getMaterialNet()));
            entity.setClassDifference(classMap.get(entity.getClassDifference()));
        }
        return list;
    }


    /**
     * 单据明细下方列表
     *
     * @param splittingOrderNumber
     * @return
     */
    @Override
    public List<WeighingFinishedMaterialProductDto> getViewList(String splittingOrderNumber) {
        //成品称重物料明细打印状态
        List<SysDictData> printStatusArray = DictUtils.getDictCache("weighing_finished_material_product_print_status");
        Map<String, String> printStatusMap = printStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //成品称重物料明细入库状态
        List<SysDictData> storageStatusArray = DictUtils.getDictCache("weighing_finished_material_product_storage_status");
        Map<String, String> storageStatusMap = storageStatusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //网型
        List<SysDictData> typeArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> typeMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //班次
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<WeighingFinishedMaterialProductDto> list = weighingFinishedMaterialProductMapper.getViewList(splittingOrderNumber);

        for (WeighingFinishedMaterialProductDto entity : list) {
            entity.setPrintStatusDict(printStatusMap.get(entity.getPrintStatus()));
            entity.setStorageStatusDict(storageStatusMap.get(entity.getStorageStatus()));
            entity.setMaterialNetDict(typeMap.get(entity.getMaterialNet()));
            entity.setClassDifferenceDict(classMap.get(entity.getClassDifference()));
        }

        return list;
    }

    /**
     * 查看(成品称重)
     *
     * @param id
     * @return
     */
    @Override
    public WeighingFinishedMaterialProductDto getViewById(Long id) {

        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        WeighingFinishedMaterialProductDto viewById = weighingFinishedMaterialProductMapper.getViewById(id);
        if ("1".equals(viewById.getPrintStatus())) {
            //获取幅宽
            List<WeighingFinishedMaterialProductDetailDto> list = weighingFinishedMaterialProductDetailService.getList(viewById.getProductNumber());
            if (list.size() > 0) {
                viewById.setWidth(list.get(0).getWidth());
            }
            viewById.setMaterialNetDict(netMap.get(viewById.getMaterialNet()));
            return viewById;
        } else {
            throw new GlobalException("仅对“未打印”的产品进行成品称重操作");
        }

    }

    /**
     * 信息打印，标签打印之后修改数据
     *
     * @param weighingFinishedMaterialProductVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateData(WeighingFinishedMaterialProductVo weighingFinishedMaterialProductVo) {
        WeighingFinishedMaterialProduct byId = getById(weighingFinishedMaterialProductVo.getId());
        //信息打印不改变列表的打印状态，只有标签打印才改变
        if (weighingFinishedMaterialProductVo.getType() == 2) {
            byId.setPrintStatus(2);
        }
        byId.setGrossWeight(weighingFinishedMaterialProductVo.getGrossWeight());
        byId.setNetWeight(weighingFinishedMaterialProductVo.getNetWeight());
        byId.setRollLength(weighingFinishedMaterialProductVo.getRollLength());
        byId.setJointNum(weighingFinishedMaterialProductVo.getJointNum());
        byId.setRemark(weighingFinishedMaterialProductVo.getRemark());
        byId.setTemplateId(weighingFinishedMaterialProductVo.getTemplateId());
        return updateById(byId);
    }

    /**
     * 查看（条码修正）
     *
     * @param id
     * @return
     */
    @Override
    public WeighingFinishedMaterialProductDto getBarCodeCorrection(Long id) {
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        WeighingFinishedMaterialProductDto viewById = weighingFinishedMaterialProductMapper.getViewById(id);
       // if ("2".equals(viewById.getPrintStatus()) && "1".equals(viewById.getStorageStatus())) {
            //获取幅宽
            List<WeighingFinishedMaterialProductDetailDto> list = weighingFinishedMaterialProductDetailService.getList(viewById.getProductNumber());
            if (list.size() > 0) {
                viewById.setWidth(list.get(0).getWidth());
            }
            viewById.setMaterialNetDict(netMap.get(viewById.getMaterialNet()));
            return viewById;
       /** }
        else {
            throw new GlobalException("仅“已打印”且“待入库”的产品才能进行条码修正");
        }*/
    }

    /**
     * 条码补打
     *
     * @param id
     * @return
     */
    @Override
    public WeighingFinishedMaterialProductDto getReprint(Long id) {
        WeighingFinishedMaterialProductDto viewById = weighingFinishedMaterialProductMapper.getViewById(id);
        if ("2".equals(viewById.getPrintStatus())) {
            //获取幅宽
            List<WeighingFinishedMaterialProductDetailDto> list = weighingFinishedMaterialProductDetailService.getList(viewById.getProductNumber());
            if (list.size() > 0) {
                viewById.setWidth(list.get(0).getWidth());
            }
            return viewById;
        } else {
            throw new GlobalException("仅“已打印”的单据可以进行条码补打");
        }
    }

    /**
     * 入库（pda）
     *
     * @param warehouseVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WarehousingDto warehousing(WarehousingVo warehouseVo) {
        WarehousingDto warehousingDto = new WarehousingDto();
        //获取信息
        WeighingFinishedMaterialProduct weighingFinishedMaterialProduct = weighingFinishedMaterialProductMapper.selectOne(new QueryWrapper<WeighingFinishedMaterialProduct>().lambda().eq(WeighingFinishedMaterialProduct::getProductNumber, warehouseVo.getInputValue()));
        if (weighingFinishedMaterialProduct.getStorageStatus() == 1 && weighingFinishedMaterialProduct.getPrintStatus() == 2) {

            if (weighingFinishedMaterialProduct.getStorageStatus() == 2) {
                warehousingDto.setResultCode("500");
                warehousingDto.setResultMessage("此产品已入库");
                return warehousingDto;
            }
            //根据制令单号获取分切制令单信息
            CutOrdersDocument cutOrdersDocument = cutOrdersDocumentMapper.selectOne(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber, weighingFinishedMaterialProduct.getSplittingOrderNumber()));

            //查询成品称重下小卷数据
            List<WeighingFinishedMaterialProductDetailDto> list = weighingFinishedMaterialProductDetailService.getList(weighingFinishedMaterialProduct.getProductNumber());

            //获取车间建模下绑定的车间
//            SysShopModelingDto warehouseing = sysShopModelingMapper.getWarehouseing(weighingFinishedMaterialProduct.getLineType());
//            Long id = warehouseing.getModelingBindingStorage();

            //车间
//            AjaxResult view = storageFegin.view(id);
//            WarehouseDto warehouseDto = JSON.parseObject(JSON.toJSONString(view.get("data")), WarehouseDto.class);

            //数据传输到“库存汇总”页面
            WmsStockInfoVo wmsStockInfoVo = new WmsStockInfoVo();
            //物料号码
            wmsStockInfoVo.setWsiMaterialNumber(weighingFinishedMaterialProduct.getProductNumber());
            //类别(1是原料2是辅料3是半成品4是成品)
            wmsStockInfoVo.setWsiCategory("4");
            //物料编码
            wmsStockInfoVo.setWsiMaterialCode(weighingFinishedMaterialProduct.getMaterialCode());
            //物料数量
            wmsStockInfoVo.setWsiMaterialNum(1);
            //库存状态
            wmsStockInfoVo.setWsiMaterialStatus(2);
            //物料等级
            wmsStockInfoVo.setWsiMaterialGrade("1");
            //批次号
            wmsStockInfoVo.setWsiMaterialBatch(weighingFinishedMaterialProduct.getBatchNum());
            //毛重
            wmsStockInfoVo.setWsiGorssWeight(Double.valueOf(weighingFinishedMaterialProduct.getGrossWeight()));
            //净重
            wmsStockInfoVo.setWsiNetWeight(Double.valueOf(weighingFinishedMaterialProduct.getNetWeight()));
            //仓库
//            wmsStockInfoVo.setWsiWarehourse(warehouseDto.getWarehouseCode());
            //客户编码
            wmsStockInfoVo.setWsiCustomCode(weighingFinishedMaterialProduct.getCustomerCode());
            //关联单号
            wmsStockInfoVo.setWsiConnectNum(cutOrdersDocument.getSplittingOrderNumber());
            //创建人
            wmsStockInfoVo.setCreateUser(SecurityUtils.getUsername());
            //长度
            wmsStockInfoVo.setWsiLength(Double.valueOf(weighingFinishedMaterialProduct.getRollLength()));
            //卷径
            wmsStockInfoVo.setWsiDiameter(cutOrdersDocument.getWindingDiameter());
            //克重
            wmsStockInfoVo.setWsiGrawWeight(list.get(0).getGramWeight());
            //厚度
            wmsStockInfoVo.setWsiThick(list.get(0).getThickness());
            //接头
            wmsStockInfoVo.setWsiJoint(list.get(0).getJoint());
            //幅宽
            wmsStockInfoVo.setWsiWidth(list.get(0).getWidth());
            //生产日期
            wmsStockInfoVo.setWsiProducedDate(new Date());
            //入库日期
            wmsStockInfoVo.setWsiReveiveTime(new Date());
            //阶别
            wmsStockInfoVo.setWsiProducedStep("3");
            AjaxResult ajaxResult = storageFegin.addWmsStock(wmsStockInfoVo);
            String code2 = ajaxResult.get("code").toString();

            if ("200".equals(code2)) {
                //分切产出后扫描入库第一卷时，完工入库单内生成一条完工入库单，单据内所属仓库为制令单所属车间所绑定的仓库（车间建模内配置）
                WipOtherAddVo wipOtherAddVo = new WipOtherAddVo();

                wipOtherAddVo.setMakingOrderNo(weighingFinishedMaterialProduct.getSplittingOrderNumber());
                wipOtherAddVo.setMaterialCode(weighingFinishedMaterialProduct.getMaterialCode());

                MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>().lambda().eq(MaterialFinished::getMaterialCode, weighingFinishedMaterialProduct.getMaterialCode()));

                wipOtherAddVo.setMaterialCategory(Integer.parseInt(materialFinished.getCategory()));
                wipOtherAddVo.setPlannedWeight(cutOrdersDocument.getPlanWeight());
                wipOtherAddVo.setWarehousTime(new Date());
                wipOtherAddVo.setReceiveType(3);
                wipOtherAddVo.setGenerationMethod(2);
                wipOtherAddVo.setMaterialCode(weighingFinishedMaterialProduct.getMaterialCode());
                wipOtherAddVo.setMaterialNumber(weighingFinishedMaterialProduct.getProductNumber());
                wipOtherAddVo.setGrossWeight(Double.parseDouble(weighingFinishedMaterialProduct.getGrossWeight()));
                wipOtherAddVo.setNetWeight(Double.parseDouble(weighingFinishedMaterialProduct.getNetWeight()));
                CutOrdersDocumentDetail documentDetail = cutOrdersDocumentDetailMapper.selectOne(new QueryWrapper<CutOrdersDocumentDetail>().lambda().eq(CutOrdersDocumentDetail::getMasterVolumeNum, weighingFinishedMaterialProduct.getMasterVolumeNumber()));
                wipOtherAddVo.setBatchNo(documentDetail.getBatchNo());


                //生成完工入库单
                AjaxResult result = storageFegin.wipOtherAdd(wipOtherAddVo);
                String code = result.get("code").toString();
                //产出的每一个成品，扫描入库后都传到对应的分切执行单页面的单据明细中
                if ("200".equals(code)) {
                    //产出重量回传到分切制令单中
                    double outputWeight = cutOrdersDocument.getOutputWeight();
                    if ((int) outputWeight == 0) {
                        cutOrdersDocument.setOutputWeight(Double.parseDouble(weighingFinishedMaterialProduct.getNetWeight()));
                    }
                    BigDecimal add = new BigDecimal(outputWeight).add(new BigDecimal(weighingFinishedMaterialProduct.getNetWeight()));
                    double v = add.doubleValue();
                    cutOrdersDocument.setOutputWeight(v);
                    //产出数量回传到分切制令单中
                    cutOrdersDocument.setOutputQuantity(cutOrdersDocument.getOutputQuantity() + 1);
                    //修改制令单数据
                    cutOrdersDocumentService.updateById(cutOrdersDocument);
                    //产出数据回传销售订单
                    BackDataVo backDataVo = new BackDataVo();
                    backDataVo.setNetWeight(Double.parseDouble(weighingFinishedMaterialProduct.getNetWeight()));
                    backDataVo.setMaterialCode(weighingFinishedMaterialProduct.getMaterialCode());
                    backDataVo.setSaleNumber(cutOrdersDocument.getSaleNumber());
                    orderFeignService.backData(backDataVo);
                    //数据回传排程计划
                    BackWeight backWeight = new BackWeight();
                    backWeight.setProductionOutputWeight(Double.parseDouble(weighingFinishedMaterialProduct.getNetWeight()));
                    backWeight.setPlanCode(weighingFinishedMaterialProduct.getPlanNumber());
                    backWeight.setMark("cp");
                    schedulingPlanFeignService.planBack(backWeight);
                    //修改物料明细入库状态为入库
                    weighingFinishedMaterialProduct.setStorageStatus(2);
                    weighingFinishedMaterialProduct.setWarehousingBy(SecurityUtils.getUsername());
                    weighingFinishedMaterialProduct.setWarehousingTime(new Date());
                    updateById(weighingFinishedMaterialProduct);
                    warehousingDto.setResultCode("200");
                    warehousingDto.setResultMessage("OK:" + "产品编码:" + warehouseVo.getInputValue() + "," + "毛重:" + weighingFinishedMaterialProduct.getGrossWeight() + "," + "净重:" + weighingFinishedMaterialProduct.getNetWeight());
                    return warehousingDto;
                }
            }
            warehousingDto.setResultMessage("入库失败");
            warehousingDto.setResultCode("500");
            return warehousingDto;
        } else {
            throw new GlobalException("仅“已打印”且“待入库”可以操作入库");
        }

    }

    /**
     * 产出统计
     *
     * @param splittingOrderNumber
     * @return
     */
    @Override
    public List<WeighingFinishedMaterialProductDto> outputStatistics(String splittingOrderNumber) {

        List<WeighingFinishedMaterialProductDto> outputStatisticsList = weighingFinishedMaterialProductMapper.getOutputStatisticsList(splittingOrderNumber);

        return outputStatisticsList;
    }

    /**
     * 新增
     *
     * @param packageLabelVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(PackageLabelVo packageLabelVo) throws Exception {

        List<RollPackingDto> rollPackList = packageLabelVo.getRollPackList();
        //获取填写的每包小卷数
        String[] packSmallRolls = packageLabelVo.getPackSmallRolls().split(",");
//        int i = 0;
//        for (String entity : packSmallRolls) {
//            i = i + Integer.parseInt(entity);
//        }
//        //勾选条数除以填写的每包小卷数
//        int i1 = rollPackList.size() / i;
//        //再乘以每包小卷数逗号分隔的个数从而获取循环次数
//        int cycleNumber = i1 * packSmallRolls.size();


//        WeighingFinishedMaterialProduct weighingFinishedMaterialProduct = new WeighingFinishedMaterialProduct();

//        List<RollPackingDto> rollPackList = packageLabelVo.getRollPackList();
        List<String> lengthList = new ArrayList<>();
        for (RollPackingDto entity : rollPackList) {
            lengthList.add(entity.getRollLength());
        }
        //去重
        List<String> collectList = lengthList.stream().distinct().collect(Collectors.toList());
        StringBuilder stringBuffer = new StringBuilder();

        for (String entity : collectList) {
            stringBuffer.append(entity).append(",");
        }
        StringBuilder lengthStr = stringBuffer.deleteCharAt(stringBuffer.length() - 1);

        //分组获取接头数
        Map<String, List<RollPackingDto>> collect = rollPackList.stream().collect(Collectors.groupingBy(RollPackingDto::getJoint));
        StringBuilder jointStr = new StringBuilder();
        for (Map.Entry<String, List<RollPackingDto>> entry : collect.entrySet()) {
            String jointResult = entry.getKey() + "*" + entry.getValue().size() + ",";
            jointStr.append(jointResult);
        }
        StringBuilder jointList = jointStr.deleteCharAt(jointStr.length() - 1);

        CutOrdersDocument cutOrdersDocument = cutOrdersDocumentMapper.selectOne(new QueryWrapper<CutOrdersDocument>().lambda().eq(CutOrdersDocument::getSplittingOrderNumber, rollPackList.get(0).getSplittingOrderNumber()));

        //获取跨天时间和班次
        AjaxResult ajaxResult = schedulingPlanFeignService.selectShiftLine(cutOrdersDocument.getLineTypeName());
        List<CalendarTeamDto> data = JSON.parseArray(JSON.toJSONString(ajaxResult.get("data")), CalendarTeamDto.class);

        if (data==null){
            throw new GlobalException("请先配置工厂日历");
        }

        Date crossSkyTime = null;
        String classDifference = null;
        for (CalendarTeamDto entity : data) {

            Date nowTime = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTime);
            Date time = calendar.getTime();
            //判断当前时间是否在开始时间和结束时间之内
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            String time2 = simpleDateFormat.format(time);
            String time3 = entity.getTeamStartTime();
            String time4 = entity.getTeamEndTime();
            if (time2.compareTo(time3) > 0 && time2.compareTo(time4) < 0) {
                //获取班组
                classDifference = entity.getTeamInfo();
                //判断是否跨天,并判断当前时间小于开始时间
                if (entity.getTeamTranssky() == 1 && time2.compareTo(time3) < 0) {
                    //如果跨天就取前一天
                    Date date = new Date();
                    //得到日历
                    Calendar calendar1 = Calendar.getInstance();
                    //把当前时间赋给日历
                    calendar1.setTime(date);
                    //设置为前一天
                    calendar1.add(Calendar.DAY_OF_MONTH, -1);
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sf.format(calendar1.getTime());
                    //得到前一天的时间
                    crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                } else {
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    String format = sf.format(new Date());
                    crossSkyTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
                }
            }
        }
        if (crossSkyTime == null && classDifference == null) {
            throw new GlobalException("未进行工厂日历配置");
        }
        String lineType = rollPackList.get(0).getLineType();
        String masterVolumeNumber = rollPackList.get(0).getMasterVolumeNumber();
        String splittingOrderNumber = rollPackList.get(0).getSplittingOrderNumber();
        String planNumber = rollPackList.get(0).getPlanNumber();
        //批次号生成，规则两位年-两位月-两位日-班次-FQ-线别编码
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yy-MM-dd");
        String format = sf.format(date);
        //班次
        List<SysDictData> classArray = DictUtils.getDictCache("scheduling_class_info");
        Map<String, String> classMap = classArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        String s = classMap.get(classDifference);

        String batchNumber = format + "-" + s + "-" + "FQ" +"-"+ lineType;

        if (packSmallRolls.length >= 1) {
            //循环 小卷数
            for (int i = 0; i < packSmallRolls.length; i++) {
                WeighingFinishedMaterialProduct weighingFinishedMaterialProduct = new WeighingFinishedMaterialProduct();
                weighingFinishedMaterialProduct.setLineType(lineType)
                        .setBatchNum(batchNumber)
                        .setMasterVolumeNumber(masterVolumeNumber)
                        .setProductNumber(feignService.splitList("CPHM"))
                        .setPrintStatus(1)
                        .setStorageStatus(1)
                        .setPackingRequirement(cutOrdersDocument.getPackingRequirement())
                        .setSplittingOrderNumber(splittingOrderNumber)
                        .setPlanNumber(planNumber)
                        .setCustomerCode(cutOrdersDocument.getCustomerCode())
                        .setMaterialCode(cutOrdersDocument.getMaterialCode())
                        .setProductTime(new Date())
                        .setCreateTime(new Date())
                        .setDeptId(SecurityUtils.getDeptId())
                        .setRollLength(lengthStr.toString())
                        .setJointNum(jointList.toString())
                        .setCrossSkyTime(crossSkyTime)
                        .setClassDifference(classDifference);
                save(weighingFinishedMaterialProduct);
                int jk1 = 0;
                int j = 0;
                //数量
                int tiAo = Integer.parseInt(packSmallRolls[i]);
                //总条数
                int packNum = rollPackList.size();
                for (; j < packNum; j++) {
                    if (tiAo > j) {

                        //保存明细信息,添加一条明细
                        List<WeighingFinishedMaterialProductDetail> detailList = new ArrayList<>();
                        WeighingFinishedMaterialProductDetail weighingFinishedMaterialProductDetail = new WeighingFinishedMaterialProductDetail();
                        weighingFinishedMaterialProductDetail.setMasterVolumeNumber(rollPackList.get(0).getMasterVolumeNumber())
                                .setSmallVolumeNumber(rollPackList.get(0).getSmallVolumeNumber())
                                .setProductNumber(weighingFinishedMaterialProduct.getProductNumber())
                                .setMaterialCode(rollPackList.get(0).getMaterialCode())
                                .setWidth(rollPackList.get(0).getWidth())
                                .setRollLength(rollPackList.get(0).getRollLength())
                                .setJoint(rollPackList.get(0).getJoint());
                        detailList.add(weighingFinishedMaterialProductDetail);
                        weighingFinishedMaterialProductDetailService.saveBatch(detailList);
                        rollPackList.remove(0);
                    } else {
                        jk1 = 1;
                        break;
                    }
                }
                if (i == packSmallRolls.length - 1) {
                    if (rollPackList.size() > 0) {
                        i = -1;
                    } else {
                        break;
                    }
                }
                if (jk1 == 1) {
                    continue;
                }
            }
        }

        //填写的每包小卷数没有逗号分隔的情况
/*        if (packSmallRolls.length == 1) {

            int size = rollPackList.size();
            String packSmallRoll = packSmallRolls[0];
            int num = size / Integer.parseInt(packSmallRoll);
            for (int i = 1; i <= num; i++) {
                WeighingFinishedMaterialProduct weighingFinishedMaterialProduct = new WeighingFinishedMaterialProduct();
                weighingFinishedMaterialProduct.setLineType(lineType)
                        .setMasterVolumeNumber(masterVolumeNumber)
                        .setProductNumber(feignService.splitList("CPHM"))
                        .setPrintStatus(1)
                        .setStorageStatus(1)
                        .setPackingRequirement(Integer.parseInt(cutOrdersDocument.getPackingRequirement()))
                        .setSplittingOrderNumber(splittingOrderNumber)
                        .setPlanNumber(planNumber)
                        .setCustomerCode(cutOrdersDocument.getCustomerCode())
                        .setMaterialCode(cutOrdersDocument.getMaterialCode())
                        .setProductTime(new Date())
                        .setCreateTime(new Date())
                        .setDeptId(SecurityUtils.getDeptId())
                        .setRollLength(lengthStr.toString())
                        .setJointNum(jointList.toString())
                        .setCrossSkyTime(crossSkyTime)
                        .setClassDifference(classDifference);
                save(weighingFinishedMaterialProduct);

                int jk2 = 0;
                int j = 0;
                for (; j <= rollPackList.size(); j++) {
                    if (Integer.parseInt(packSmallRoll) > j) {
                        //保存明细信息,添加一条明细
                        List<WeighingFinishedMaterialProductDetail> detailList = new ArrayList<>();
                        WeighingFinishedMaterialProductDetail weighingFinishedMaterialProductDetail = new WeighingFinishedMaterialProductDetail();
                        weighingFinishedMaterialProductDetail.setMasterVolumeNumber(rollPackList.get(0).getMasterVolumeNumber())
                                .setSmallVolumeNumber(rollPackList.get(0).getSmallVolumeNumber())
                                .setProductNumber(weighingFinishedMaterialProduct.getProductNumber())
                                .setMaterialCode(rollPackList.get(0).getMaterialCode())
                                .setWidth(rollPackList.get(0).getWidth())
                                .setRollLength(rollPackList.get(0).getRollLength())
                                .setJoint(rollPackList.get(0).getJoint());
                        detailList.add(weighingFinishedMaterialProductDetail);
                        weighingFinishedMaterialProductDetailService.saveBatch(detailList);
                        rollPackList.remove(0);
                    } else {
                        jk2 = 1;
                        break;
                    }
                }
                if (rollPackList.size() == 0) {
                    break;
                }
                if (jk2 == 1) {
                    continue;
                }
            }
        }*/
        return true;
    }


    /**
     * 根据产品号码获取详情(feign调用)
     *
     * @param materialNumber
     * @return
     */
    @Override
    public WeighingFinishedMaterialProductDto getWeighingFinishedData(String materialNumber) {
        return weighingFinishedMaterialProductMapper.getWeighingFinishedData(materialNumber);
    }

    /**
     * 根据产品号码获取详情(完工入库 feign调用)
     *
     * @param materialNumber
     * @return
     */
    @Override
    public WeighingFinishedMaterialProductDto getFinishedData(String materialNumber) {
        return weighingFinishedMaterialProductMapper.getFinishedData(materialNumber);
    }

    /**
     * 根据母卷号码查询成品称重详情（产品追溯feign）
     * @param masterVolumeNumber
     * @return
     */
    @Override
    public List<TraceabilityProductDto> selectWeighingFinishedMaterialProductList(String masterVolumeNumber) {
        return weighingFinishedMaterialProductMapper.selectWeighingFinishedMaterialProductList(masterVolumeNumber);
    }

    /**
     * 通过小卷号码查询成品称重信息（产品追溯小卷基础信息feign）
     * @param smallVolumeNumber
     * @return
     */
    @Override
    public SmallRollFoundationDto selectBySmallVolumeNumber(String smallVolumeNumber) {
        return weighingFinishedMaterialProductMapper.selectBySmallVolumeNumber(smallVolumeNumber);
    }


}
